package com.yunquan.ohana.ui.history.details

import android.graphics.Color
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.setPadding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.google.gson.Gson
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.listener.VideoAllCallBack
import com.yunquan.ohana.BR
import com.yunquan.ohana.R
import com.yunquan.ohana.adapter.ModelRecyclerAdapter
import com.yunquan.ohana.adapter.ModelViewHolder
import com.yunquan.ohana.base.ui.BaseActivity
import com.yunquan.ohana.databinding.ActivityDetailsBinding
import com.yunquan.ohana.entity.FileGroupEntity
import com.yunquan.ohana.entity.LocalFileEntity
import com.yunquan.ohana.entity.LocalFrameEntity
import com.yunquan.ohana.ui.history.details.adapter.DetailsPagerAdapter
import com.yunquan.ohana.ui.history.preview.HistoryPreviewActivity
import com.yunquan.ohana.utils.GlideApp
import com.yunquan.ohana.utils.StringUtils
import com.yunquan.ohana.utils.Utils
import com.yunquan.ohana.view.SampleCoverVideo
import java.io.File
import java.text.SimpleDateFormat
import java.util.Locale

class DetailsActivity : BaseActivity<ActivityDetailsBinding, DetailsViewModel>() {

    private var mData: FileGroupEntity? = null
    private var mCurrentIndex: Int = 0

    private var mPagerAdapter: DetailsPagerAdapter? = null
    private var mImageAdapter: ModelRecyclerAdapter<LocalFileEntity>? = null
    private var mDeviceAdapter: ModelRecyclerAdapter<LocalFrameEntity>? = null

    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_details
    }

    override fun initVariableId(): Int {
        return BR.detailsViewModel
    }

    override fun onResume() {
        super.onResume()
        GSYVideoManager.onResume(false)
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onDestroy() {
        GSYVideoManager.releaseAllVideos()
        super.onDestroy()
    }

    override fun initParam() {
        super.initParam()
        window.statusBarColor = resources.getColor(R.color.background)
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }

    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)
        val bundle = intent.extras
        bundle?.let {
            mData = it.getSerializable("data") as FileGroupEntity?
        }
        setHeaderView()
        setPhotosView()
        setDeviceView()
    }

    private fun setHeaderView() {
        if (mData?.photos == null) return
        mPagerAdapter = DetailsPagerAdapter(mData!!.photos)
        mPagerAdapter!!.setOnItemClickListener {
            val jsonData = Gson().toJson(mData!!.photos)
            val bundle = Bundle()
            bundle.putInt("index", it)
            bundle.putString("data", jsonData)
            startActivity(HistoryPreviewActivity::class.java, bundle)
        }
        binding!!.viewPager.adapter = mPagerAdapter
        binding!!.viewPager.offscreenPageLimit = 1
        binding!!.viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        binding!!.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mCurrentIndex = position
                mImageAdapter?.notifyDataSetChanged()
            }
        })
    }

    private fun setPhotosView() {
        if (mData?.photos == null) return
        val list = mutableListOf<LocalFileEntity>()
        list.addAll(mData!!.photos)
        mImageAdapter = ModelRecyclerAdapter(this, list, R.layout.item_crop_image)
        mImageAdapter?.setBindViewListener(object : ModelRecyclerAdapter.ModelBindViewListener<LocalFileEntity> {
            override fun onBindView(holder: ModelViewHolder, item: LocalFileEntity, position: Int) {
                holder.setVisibility(R.id.iv_edit, View.INVISIBLE)
                val root = holder.getViewAtId<ConstraintLayout>(R.id.cl_root)
                val pic = holder.getViewAtId<ImageView>(R.id.iv_pic)

                var path: String? = null
                var file: File? = null
                if (item.type == 1) {
                    if (item.localCropPath != null) {
                        file = File(item.localCropPath)
                        if (!file.exists() && item.localFilePath != null) {
                            file = File(item.localFilePath)
                        }
                    } else if (item.localFilePath != null) {
                        file = File(item.localFilePath)
                    } else {
                        path = item.fileUrl
                    }
                } else {
                    if (item.thumbnail != null) {
                        file = File(item.thumbnail!!)
                    } else {
                        path = item.videoImgUrl ?: item.fileUrl
                    }
                }
                val glide = if (path != null) {
                    GlideApp.with(this@DetailsActivity).load(path)
                } else if (file?.exists() == true) {
                    GlideApp.with(this@DetailsActivity).load(file)
                } else {
                    GlideApp.with(this@DetailsActivity).load(R.mipmap.ic_default_image)
                }
                glide.override(200, 300)
                    .transition(DrawableTransitionOptions.withCrossFade())
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .skipMemoryCache(false)
                    .error(R.mipmap.ic_default_image)
                    .into(pic)

                if (position == mCurrentIndex) {
                    root.setBackgroundResource(R.drawable.bg_r10_14)
                    root.setPadding(Utils.instance.dp2px(2f))
                } else {
                    root.setBackgroundColor(Color.TRANSPARENT)
                    root.setPadding(Utils.instance.dp2px(0f))
                }
                root.setOnClickListener {
                    mCurrentIndex = position
                    binding!!.viewPager.setCurrentItem(position, false)
                    mImageAdapter?.notifyItemChanged(position)
                }
            }
        })
        binding!!.rvContent.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        binding!!.rvContent.adapter = mImageAdapter
    }

    private fun setDeviceView() {
        if (mData?.frames == null) return
        val list = mutableListOf<LocalFrameEntity>()
        list.addAll(mData!!.frames)
        mDeviceAdapter = ModelRecyclerAdapter(this, list, R.layout.item_receiving_status)
        mDeviceAdapter?.setBindViewListener(object : ModelRecyclerAdapter.ModelBindViewListener<LocalFrameEntity> {
            override fun onBindView(holder: ModelViewHolder, item: LocalFrameEntity, position: Int) {
                holder.setText(R.id.tv_frames_name, item.name ?: "")
                    .setText(R.id.tv_frames_location, item.location ?: "")
            }
        })
        binding!!.rvDevices.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        binding!!.rvDevices.adapter = mDeviceAdapter
    }
}